var RECRUIT_API_KEY = 'f6aee6dbf3823d61';
var map;
var price_map = {};
var REGION_MAP = {
  'Europe': {
    center: '53.330873,24.257813',
    countries: {
      'TR': '38.9637450,35.2433220',
      'GR': '39.0742080,21.8243120',
      'PT': '39.39987199999999,-8.2244540',
      'ES': '40.46366700000001,-3.749220',
      'IT': '41.871940,12.567380',
      'FR': '46.2276380,2.2137490',
      'CZ': '49.81749199999999,15.4729620',
      'DE': ' 51.1656910,10.4515260',
      'NL': '52.1326330,5.291265999999999',
      'GB': '55.3780510,-3.4359730',
      'FI': '66.84868510,42.13975290'
    }
  },
  'Africa': {
    center: '6.83917,24.433594',
    countries: {
      'KE': '0.428463,37.875366'
    }
  },
  'Asia': {
    center: '38.272689,91.933594',
    countries: {
      'KR': '36.633162,128.012695',
      'CN': '34.161818,103.271484',
      'TH': '34.161818,103.271484',
      'IN': '19.062118,75.849609',
      'VN': '13.667338,108.369141'
    }
  },
  'Australia': {
    center: '-24.686952,135',
    countries: {
      'AU': '-25.799891,136.054688'
    }
  },
  'North America': {
    center: '51.727028,-104.589844',
    countries: {
      'US': '40.313043,-100.019531'
    }
  },
  'South America': {
    center: '-19.311143,-59.0625',
    countries: {
      'BR': '-8.407168,-54.755859'
    }
  }
};

$(function() {
  var BING_API_KEY = 'Agj3docoxBO1Ry7fCgQRAeNfagXtF2d4BjPTz00HVErg0e1irSZXjn-oKka98e-t';

  // マップを作成
  map = new Microsoft.Maps.Map(document.getElementById('map'), {
    credentials: BING_API_KEY
  });

  // 拡大率が変わったら表示する内容を変えます。
  Microsoft.Maps.Events.addHandler(map, 'viewchangeend', function() {
    var zoom = map.getZoom();
    if (zoom < 3) {
      showRegionPrice();
    } else {
      showCountryPrice();
    }
  });
  loadPrice();
  function is_mobile () {
	  var useragents = [
	    'iPhone',         // Apple iPhone
	    'iPod',           // Apple iPod touch
	    'Android',        // 1.5+ Android
	    'dream',          // Pre 1.5 Android
	    'CUPCAKE',        // 1.5+ Android
	    'blackberry9500', // Storm
	    'blackberry9530', // Storm
	    'blackberry9520', // Storm v2
	    'blackberry9550', // Storm v2
	    'blackberry9800', // Torch
	    'webOS',          // Palm Pre Experimental
	    'incognito',      // Other iPhone browser
	    'webmate'         // Other iPhone browser
	  ];
	  var pattern = new RegExp(useragents.join('|'), 'i');
	  return pattern.test(navigator.userAgent);
  }
  if (is_mobile()) {
    setTimeout(function() {
	    $('#header').slideUp();
	},2000);
		
  }
});

function loadPrice() {
  var region, country;
  price_map = {};
  for (region in REGION_MAP) {
    for(country in REGION_MAP[region].countries) {
      var url = 'http://webservice.recruit.co.jp/ab-road/tour/v1/?key=' + RECRUIT_API_KEY + '&order=1&count=1&area=EUR&country=' + country + '&format=jsonp&callback=?';
      (function(country, url) {
        $.getJSON(url, function(json, status) {
          price_map[country] = {
            'price': json.results.tour[0].price.min, // 価格
            'url': json.results.tour[0].urls.pc,
            'title': json.results.tour[0].title
          };
          var zoom = map.getZoom();
          if (zoom < 3) {
            showRegionPrice();
          } else {
            showCountryPrice();
          }
        });
      })(country, url);
    }
  }
}

// 地域ごとの価格を表示します。
function showRegionPrice() {
  var region, country;
  map.entities.clear();
  for (region in REGION_MAP) {
    var min_price = 100000000;
    for(country in REGION_MAP[region].countries) {
      if (!price_map[country]) {
        continue;
      }
      if (price_map[country].price < min_price) {
        min_price = price_map[country].price;
      }
    }
    var latLongArray = REGION_MAP[region].center.split(',');
    var latVal = parseFloat(latLongArray[0]);
    var longVal = Microsoft.Maps.Location.normalizeLongitude(parseFloat(latLongArray[1]));
    var loc = new Microsoft.Maps.Location(latVal, longVal);
    var infoboxOptions = {
      title: min_price, // 価格
      width: 80, height: 30,
      showCloseButton: false
    }; 
    var infobox = new Microsoft.Maps.Infobox(loc, infoboxOptions);
    (function setClickEvent(loc) {
      Microsoft.Maps.Events.addHandler(infobox, 'click', function() {
        map.setView({zoom: 3, center: loc});
      });
    })(loc);
    map.entities.push(infobox);
  }
}

//国ごとの価格を表示します。
function showCountryPrice() {
  map.entities.clear();
  var region, country;
  for (region in REGION_MAP) {
    for(country in REGION_MAP[region].countries) {
      var latLongArray = REGION_MAP[region].countries[country].split(',');
      var latVal = parseFloat(latLongArray[0]);
      var longVal = Microsoft.Maps.Location.normalizeLongitude(parseFloat(latLongArray[1]));
      var loc = new Microsoft.Maps.Location(latVal, longVal);
      var url = 'http://webservice.recruit.co.jp/ab-road/tour/v1/?key=' + RECRUIT_API_KEY + '&order=1&count=1&area=EUR&country=' + country + '&format=jsonp&callback=?';

      var infoboxOptions = {
        title: addFigure(price_map[country].price), // 価格
        width: 80, height: 30,
        showCloseButton: false
      }; 
      var infobox = new Microsoft.Maps.Infobox(loc, infoboxOptions);
      Microsoft.Maps.Events.addHandler(infobox, 'mouseenter', function() {
        this.target.setOptions({ zIndex: 1 });
      });
      Microsoft.Maps.Events.addHandler(infobox, 'mouseleave', function() {
        this.target.setOptions({ zIndex: 0 });
      });

      (function(info) {
        Microsoft.Maps.Events.addHandler(infobox, 'click', function() {
          if (window.confirm("詳細へ移動しますか？\n" + info.title + "\n\\" + addFigure(info.price))) {
            window.open(info.url, "detail");
          }
        });
      })(price_map[country]);

      map.entities.push(infobox);
    }
  }
}


function addFigure(str) {
  var num = new String(str).replace(/,/g, "");
  while(num != (num = num.replace(/^(-?\d+)(\d{3})/, "$1,$2")));
  return num;
}
